<?php
namespace Scaffold\Verify;
use Swiftx\Http\Session;

/**
 * ---------------------------------------------------------------------------------------------------------------
 * 中国移动通信SMS短信发送接口
 * ---------------------------------------------------------------------------------------------------------------
 * @author		胡永强  <odaytudio@gmailcom>
 * @since		2015-02-25
 * @copyright	Copyright (c) 2014-2015 Swiftx Inc.
 * ---------------------------------------------------------------------------------------------------------------
 */
class Sms {

    /**
     * 获取短信验证码
     * @param $number 手机号
     * @param $tempatle 短信模板
     * @throws \Exception\Scaffold\Verify\Sms
     */
    public static function Send($number, $tempatle){
        // 获取有效的短信发送记录
        $history = $GLOBALS->DB->Table('Table_Verify_Message')->Where('Phone',$number)->Where('LastTime','<=','60')->Row;
        // 存在保护期内的验证码短信
        if($history){
            $time = 60 - time() + $history['LastTime'];
            $exception = new \Exception\Scaffold\Verify\Sms('请在'.$time.'秒后重新提交',301);
            throw $exception;
        }
        // 不存在保护期内的短信
        else{
            // 生成随机数和短信
            $key = rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9);
            $message = str_replace('{$code}', $key, $tempatle);
            // 发送短信验证码
            $sms = new \Fam520\Message\Sms();
            $sms->Number($number);
            $sms->Content($message);
            $sms->Send();
            // 添加短信发送记录
            $GLOBALS->DB->Table('Table_Verify_Message')->Where('Phone',$number)->Delete;
            $GLOBALS->DB->Table('Table_Verify_Message')->Insert(array(
                'Phone' => $number,
                'LastTime' => time(),
                'Value' => $key
            ));
            Session::Set('Verify.Mobile',$number);
        }
    }

    /**
     * 验证短信验证码
     * @param $code
     * @return bool
     */
    public static function Check($number,$code){
        // 用户当前SESSION过期
        if(Session::Exists('Verify.Mobile') and Session::Value('Verify.Mobile')==$number){
            // 用户有效的短信发送记录
            $history = $GLOBALS->DB->Table('Table_Verify_Message')->Where('Phone',Session::Value('Verify.Mobile'))->Where('LastTime','<=','1800')->Row;
            $GLOBALS->DB->Table('Table_Verify_Message')->Where('Phone',Session::Value('Verify.Mobile'))->Delete;
            // 有效期内发送记录存在
            return $history and ($history['Value']==$code);
        }
        return false;
    }
}
